package com.free4inno.knowledgems.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * Author: HaoYi.
 * Date: 2020/9/19.
 */

@Slf4j
public class StringUtils {

    /**
     * @param str 从数据库中取出要返回前端的字符串
     * @return 将双引号替换完成的字符串, 将换行符替换成<br />
     */
    public static String inputStringFormat(String str) {
        log.info(LogUtils.parse("字符串格式化", "将双引号替换完成的字符串, 将换行符替换成br"));
        if (str == null || str.length() == 0) {
            return "";
        }
        return str.replaceAll("\r\n", "<br/>")
                .replaceAll("\n\r", "<br/>")
                .replaceAll("\n", "<br/>")
                .replaceAll("\r", "<br/>");
//        .replaceAll("\"", "&quot;")
    }

    // 生成随机字母数字组合的字符串（用于openApi生成随机appKey）
    public static String getRandomString(int length) {
        log.info(LogUtils.parse("字符串生成", "生成随机串，为openApi生成随机appKey"));
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            if ("char".equalsIgnoreCase(charOrNum)) {
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (choice + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }
}
